package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/find-largest-value-in-each-tree-row/description/
 *
 * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值。
 */
public class _9LetCode515_在每个树行中找最大值 {

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                max = Math.max(max, root.val);
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
            res.add(max);
        }
        return res;
    }
}
